package com.pzh.xzh.uaa.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class PasswordHandler extends DaoAuthenticationProvider {
    private final static String salt="Zgr!#@%904ed65FSrg*(AE";
    public PasswordHandler(UserDetailsService userDetailsService){
        setUserDetailsService(userDetailsService);
        setPasswordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        if (authentication.getCredentials()!=null){
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String password = authentication.getCredentials().toString();
            // 数据库密码（应该是加密后的）
            String dbPassword = userDetails.getPassword();
            //System.out.println(encoder.encode(password+salt));
            //log.info("加密前：{}，加密后：{}",password + salt, encoder.encode(password + salt));
            // encode(加密前,加密后)
            boolean isMatch = encoder.matches(password + salt, dbPassword);
            if (!isMatch) {
                throw new BadCredentialsException("BadCredentialsException：密码错误！");
            }
        }
    }
}
